/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.shardingsphere.infra.route.engine;

import org.apache.shardingsphere.infra.annotation.HighFrequencyInvocation;
import org.apache.shardingsphere.infra.binder.context.extractor.SQLStatementContextExtractor;
import org.apache.shardingsphere.infra.config.props.ConfigurationProperties;
import org.apache.shardingsphere.infra.exception.kernel.syntax.hint.DataSourceHintNotExistsException;
import org.apache.shardingsphere.infra.hint.HintManager;
import org.apache.shardingsphere.infra.hint.HintValueContext;
import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;
import org.apache.shardingsphere.infra.metadata.database.resource.unit.StorageUnit;
import org.apache.shardingsphere.infra.metadata.database.rule.RuleMetaData;
import org.apache.shardingsphere.infra.route.SQLRouter;
import org.apache.shardingsphere.infra.route.SQLRouter.Type;
import org.apache.shardingsphere.infra.route.context.RouteContext;
import org.apache.shardingsphere.infra.route.context.RouteMapper;
import org.apache.shardingsphere.infra.route.context.RouteUnit;
import org.apache.shardingsphere.infra.route.engine.tableless.router.TablelessSQLRouter;
import org.apache.shardingsphere.infra.route.lifecycle.DecorateSQLRouter;
import org.apache.shardingsphere.infra.route.lifecycle.EntranceSQLRouter;
import org.apache.shardingsphere.infra.rule.ShardingSphereRule;
import org.apache.shardingsphere.infra.session.query.QueryContext;
import org.apache.shardingsphere.infra.spi.type.ordered.OrderedSPILoader;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;

/**
 * SQL route engine.
 */
@HighFrequencyInvocation
public final class SQLRouteEngine {

    //配置属性，用于在路由过程中提供必要的配置信息
    private final ConfigurationProperties props;
    //存储针对数据节点（如表）的路由器映射。
    @SuppressWarnings("rawtypes")
    private final Map<ShardingSphereRule, SQLRouter> dataNodeRouters;
    //存储针对数据源（如数据库实例）的路由器映射。
    @SuppressWarnings("rawtypes")
    private final Map<ShardingSphereRule, SQLRouter> dataSourceRouters;
    
    @SuppressWarnings("rawtypes")
    public SQLRouteEngine(final Collection<ShardingSphereRule> rules, final ConfigurationProperties props) {
        // 将传入的配置属性赋值给类的成员变量props
        this.props = props;

        // 使用OrderedSPILoader加载SQLRouter类型的服务，根据传入的rules参数进行过滤
        // 返回一个Map，其中键为ShardingSphereRule对象，值为对应的SQLRouter对象
        Map<ShardingSphereRule, SQLRouter> routers = OrderedSPILoader.getServices(SQLRouter.class, rules);

        // 调用filterRouters方法，传入routers和Type.DATA_NODE作为参数
        // 过滤出Type为DATA_NODE的SQLRouter对象，并将结果赋值给dataNodeRouters成员变量
        dataNodeRouters = filterRouters(routers, Type.DATA_NODE);

        // 调用filterRouters方法，传入routers和Type.DATA_SOURCE作为参数
        // 过滤出Type为DATA_SOURCE的SQLRouter对象，并将结果赋值给dataSourceRouters成员变量
        dataSourceRouters = filterRouters(routers, Type.DATA_SOURCE);

        System.out.println("dataNodeRouters: " + dataNodeRouters);
    }

    
    /**
     * 根据类型过滤SQL路由器
     *
     * @param routers 原始路由器映射，键为ShardingSphereRule，值为SQLRouter
     * @param type 需要过滤的类型
     * @return 过滤后的路由器映射，键为ShardingSphereRule，值为SQLRouter
     */
    @SuppressWarnings("rawtypes")
    private Map<ShardingSphereRule, SQLRouter> filterRouters(final Map<ShardingSphereRule, SQLRouter> routers, final Type type) {
        // 创建一个LinkedHashMap来存储结果，以保持插入顺序
        Map<ShardingSphereRule, SQLRouter> result = new LinkedHashMap<>();

        // 遍历routers集合中的每个元素
        for (Entry<ShardingSphereRule, SQLRouter> entry : routers.entrySet()) {
            // 如果当前元素的值（SQLRouter对象）的类型与传入的type相等
            if (type == entry.getValue().getType()) {
                // 将当前元素添加到结果集合中
                result.put(entry.getKey(), entry.getValue());
            }
        }

        // 返回过滤后的结果集合
        return result;
    }

    
    /**
     * 根据查询上下文、全局规则元数据和分片数据库进行路由。
     *
     * @param queryContext 查询上下文
     * @param globalRuleMetaData 全局规则元数据
     * @param database 分片数据库
     * @return 路由上下文
     */
    public RouteContext route(final QueryContext queryContext, final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database) {
        // 创建路由上下文对象
        RouteContext result = new RouteContext();

        // 根据提示值查找数据源名称
        Optional<String> dataSourceName = findDataSourceByHint(queryContext.getHintValueContext(), database.getResourceMetaData().getStorageUnits());
        // 如果找到了数据源名称
        if (dataSourceName.isPresent()) {
            // 将路由单元添加到路由上下文中
            result.getRouteUnits().add(new RouteUnit(new RouteMapper(dataSourceName.get(), dataSourceName.get()), Collections.emptyList()));
            // 返回路由上下文
            return result;
        }

        // 从SQL语句中提取表名
        Collection<String> tableNames = SQLStatementContextExtractor.getTableNames(database, queryContext.getSqlStatementContext());

        // 执行路由逻辑
        result = route(queryContext, globalRuleMetaData, database, dataNodeRouters, tableNames, result);

        // 处理无表SQL的路由
        result = new TablelessSQLRouter().route(queryContext, globalRuleMetaData, database, tableNames, result);

        // 执行数据源路由逻辑
        result = route(queryContext, globalRuleMetaData, database, dataSourceRouters, tableNames, result);

        // 如果没有路由单元，并且数据库只有一个存储单元
        if (result.getRouteUnits().isEmpty() && 1 == database.getResourceMetaData().getStorageUnits().size()) {
            // 获取唯一的数据源名称
            String singleDataSourceName = database.getResourceMetaData().getStorageUnits().keySet().iterator().next();
            // 将路由单元添加到路由上下文中
            result.getRouteUnits().add(new RouteUnit(new RouteMapper(singleDataSourceName, singleDataSourceName), Collections.emptyList()));
        }

        // 返回路由上下文
        return result;
    }

    
    @SuppressWarnings({"unchecked", "rawtypes"})
    private RouteContext route(final QueryContext queryContext, final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database,
                               final Map<ShardingSphereRule, SQLRouter> routers, final Collection<String> tableNames, final RouteContext routeContext) {
        // 初始化结果变量
        RouteContext result = routeContext;

        // 遍历routers集合
        for (Entry<ShardingSphereRule, SQLRouter> entry : routers.entrySet()) {
            // 如果结果集中的路由单元为空，并且当前路由器是EntranceSQLRouter的实例
            if (result.getRouteUnits().isEmpty() && entry.getValue() instanceof EntranceSQLRouter) {
                // 使用EntranceSQLRouter创建新的路由上下文
                result = ((EntranceSQLRouter) entry.getValue()).createRouteContext(queryContext, globalRuleMetaData, database, entry.getKey(), tableNames, props);
            }
            // 如果当前路由器是DecorateSQLRouter的实例
            else if (entry.getValue() instanceof DecorateSQLRouter) {
                // 使用DecorateSQLRouter装饰现有的路由上下文
                ((DecorateSQLRouter) entry.getValue()).decorateRouteContext(result, queryContext, database, entry.getKey(), tableNames, props);
            }
        }

        // 返回最终的路由上下文
        return result;
    }

    
    private Optional<String> findDataSourceByHint(final HintValueContext hintValueContext, final Map<String, StorageUnit> storageUnits) {
        // 如果HintManager已经实例化并且存在数据源名称，则返回该名称
        // 否则，通过hintValueContext查找数据源名称
        Optional<String> result = HintManager.isInstantiated() && HintManager.getDataSourceName().isPresent() ? HintManager.getDataSourceName() : hintValueContext.findHintDataSourceName();

        // 如果结果存在且storageUnits中不包含该数据源名称，则抛出异常
        if (result.isPresent() && !storageUnits.containsKey(result.get())) {
            // 抛出异常，提示数据源名称不存在
            throw new DataSourceHintNotExistsException(result.get());
        }

        // 返回结果
        return result;
    }

}
